import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

// API响应接口
export interface ApiResponse<T = any> {
  success: boolean
  message: string
  data: T
  error?: string
  timestamp: string
}

// 创建axios实例
export const apiClient: AxiosInstance = axios.create({
  baseURL: process.env.REACT_APP_API_BASE_URL || 'http://localhost:3001',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 添加认证token
    const token = localStorage.getItem('auth_token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 添加请求ID用于追踪
    if (config.headers) {
      config.headers['X-Request-ID'] = generateRequestId()
    }
    
    return config
  },
  (error) => {
    console.error('Request interceptor error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    // 检查业务状态码
    if (response.data && !response.data.success) {
      console.warn('API business error:', response.data.message)
    }
    return response
  },
  (error) => {
    // 统一错误处理
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          localStorage.removeItem('auth_token')
          window.location.href = '/login'
          break
        case 403:
          console.error('Access forbidden:', data?.message || '权限不足')
          break
        case 404:
          console.error('Resource not found:', data?.message || '资源不存在')
          break
        case 422:
          console.error('Validation error:', data?.message || '数据验证失败')
          break
        case 429:
          console.error('Rate limit exceeded:', data?.message || '请求频率超限')
          break
        case 500:
          console.error('Server error:', data?.message || '服务器内部错误')
          break
        case 502:
        case 503:
        case 504:
          console.error('Service unavailable:', data?.message || '服务暂时不可用')
          break
        default:
          console.error(`HTTP ${status}:`, data?.message || error.message)
      }
    } else if (error.request) {
      // 网络错误
      console.error('Network error:', error.message)
    } else {
      // 请求配置错误
      console.error('Request config error:', error.message)
    }
    
    return Promise.reject(error)
  }
)

// 生成请求ID
function generateRequestId(): string {
  return `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 导出默认实例
export default apiClient